package com.tengju.bff.health;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

@Slf4j
public class HttpUtil {

    private HttpUtil() {
    }

    /**
     * get方式请求
     */
    public static Response get(String url) throws IOException {
        Request request = new Request.Builder().url(url)
                .build();
        Response response = new OkHttpClient().newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException("请求有错：" + response);
        return response;
    }

    /**
     * post方式请求
     */
    public static String post(String url, RequestBody body) throws IOException {
        Request request = new Request.Builder().url(url)
                .post(body).build();
        Response response = new OkHttpClient().newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException("请求有错：" + response);
        return Optional.ofNullable(response.body())
                .map(responseBody -> {
                    try {
                        return responseBody.string();
                    } catch (IOException e) {
                        log.error("请求结果解析失败", e);
                        return null;
                    }
                })
                .orElse(null);
    }

    public static String postXML(String url, String xml) throws IOException {
        RequestBody body = RequestBody
                .create(MediaType.parse("text/xml;charset=" + StandardCharsets.UTF_8), xml);
        return post(url, body);
    }

}
